﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DomainInfoLib
{
    public class CnolnicAPI : IWebAPI
    {
        private static bool? ProcessAvaliableStr(string avaliableStr)
        {
            if (string.IsNullOrEmpty(avaliableStr))
            {
                return null;
            }

            int pos = avaliableStr.IndexOf(';');
            
            if (pos==-1)
            {
                throw new Exception("CnolnicAPI:"+avaliableStr);
            }

            string key = avaliableStr.Substring(pos-1, 1);

            if (key == "1")
            {
                return true;
            }

            return false;
        }


        private static string ProcessXmlStr(string XmlStr)
        {
            try
            {
                if (string.IsNullOrEmpty(XmlStr)) return "";



                return XmlStr;
            }
            catch
            {

                return "";
            }



        }

        public string GetUrl(string DomainName)
        {
            int pos = DomainName.IndexOf('.');

            string keyword = DomainName.Substring(0, pos);

            string domain = DomainName.Substring(pos+1, DomainName.Length - pos-1);

            string url = string.Format("http://www.cnolnic.com/cgi-bin/domainquery.cgi?flag=1&domainname={0}&{1}=on", keyword, domain.Trim());
            
            return url;
        }

        public RegisterInfo GetResponseByWebAPI(string DomainName)
        {
 
            string url = GetUrl(DomainName);

            string xmlstr = BaseInfo.CallWebPage(url, null, null);

            if (xmlstr=="domainquerymsg='请至少选择一种类型'")
            {
                throw new Exception(url);
            }

            string avaliableStr = ProcessXmlStr(xmlstr);

            bool? Avaliable = ProcessAvaliableStr(avaliableStr);

            if (!Avaliable.HasValue)
            {
                return null;
            }

            return RegisterInfo.BuildRegisterInfo(DomainName, xmlstr, Avaliable, this.GetType().Name);
        }
    }
}
